#ifndef __UTIL__
#define __UTIL__

#include <GLTools.h>
#include <GLFrame.h> // needed in both planet and glview

#define CheckShader(_shader, _msg) if (_shader == NULL) MessageBox(NULL, _msg, "Problem with shader", MB_OK);
#define CheckUniform(_uniform,_msg) if (_uniform < 0) MessageBox(NULL, _msg, "Problem with Uniform", MB_OK);

static void GetNormalMatrix(M3DMatrix33f mNormal, const M3DMatrix44f mModelView){
	M3DVector4f vColumn;

	m3dGetMatrixColumn44(vColumn, mModelView, 0);
	m3dNormalizeVector3(vColumn);
	m3dSetMatrixColumn33(mNormal, vColumn, 0);

	m3dGetMatrixColumn44(vColumn, mModelView, 1);
	m3dNormalizeVector3(vColumn);
	m3dSetMatrixColumn33(mNormal, vColumn, 1);

	m3dGetMatrixColumn44(vColumn, mModelView, 2);
	m3dNormalizeVector3(vColumn);
	m3dSetMatrixColumn33(mNormal, vColumn, 2);

}

static bool LoadBMPAsTexture(const char* szFileName, GLenum filter, GLenum wrapMode){

	GLbyte* pBits;
	int nWidth, nHeight;

	pBits = gltReadBMPBits(szFileName, &nWidth, &nHeight);
	if (pBits == NULL)
	{
		MessageBox(NULL, "Can't load Texture", szFileName, MB_OK);
		return false;
	}


	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, nWidth, nHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pBits);

	if (filter != GL_LINEAR && filter != GL_NEAREST)
		glGenerateMipmap(GL_TEXTURE_2D);

	delete [] pBits;

	return true;
}

static bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode){
	GLbyte* bits;
	int width, height, components;
	GLenum format;

	bits = gltReadTGABits(szFileName, &width, &height, &components, &format);
	if (bits == NULL)
	{
		MessageBox(NULL, "Can't load Texture", szFileName, MB_OK);
		return false;
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);

	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexImage2D(GL_TEXTURE_2D, 0, components, width, height, 0, format, GL_UNSIGNED_BYTE, bits);


	delete[] bits;

	if (minFilter == GL_LINEAR_MIPMAP_LINEAR ||
		minFilter == GL_LINEAR_MIPMAP_NEAREST ||
		minFilter == GL_NEAREST_MIPMAP_LINEAR ||
		minFilter == GL_NEAREST_MIPMAP_NEAREST)
		glGenerateMipmap(GL_TEXTURE_2D);

	return true;
}

#endif